﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MeTalker.Aide.data;
using MeTalker.Aide.Mode;
using MeTalker.Securitys.Cryptography;
using System.IO;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using System.Threading;

namespace MeTalker.Aide.Forms
{
    internal partial class frmAddLicense : MeForm
    {
        Account account;
        string strParam;
        public frmAddLicense()
        {
            InitializeComponent();

        }
        public frmAddLicense(string account)
            : this()
        {
            txtAccount.Text = account;

        }

        public frmAddLicense(Account account)
            : this()
        {
            this.account = account;
            txtAppSecret.Text = account.AppSecret;
            txtAppKey.Text = account.AppKey;
            txtAccount.Text = account.AccountId;
        }

        bool CheckData() {
            if (string.IsNullOrEmpty(txtAccount.Text))
            {
                MeMessageBox.ShowInformation("掌柜旺旺账号不能为空!");
                return false;
            }
            if (string.IsNullOrEmpty(txtAppKey.Text))
            {
                MeMessageBox.ShowInformation("店铺AppKey不能为空!");
                return false;
            }
            if (string.IsNullOrEmpty(txtAppSecret.Text))
            {
                MeMessageBox.ShowInformation("店铺AppSecret不能为空!");
                return false;
            }
           
            return true;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }
            if (string.IsNullOrEmpty(txtTopSession.Text))
            {
                MeMessageBox.ShowInformation("店铺授权密钥不能为空!");
                return;
            }
            //TestAccount();
            string nick;
            if (TestAccount(txtAccount.Text, txtAppKey.Text, txtAppSecret.Text, txtTopSession.Text, out  nick))
            {
                if (account == null)
                {
                    var ds = from temp in DataFactory.Accounts where temp.AccountId.Equals(txtAccount.Text) select temp;
                    if (ds.Count() > 0)
                    {
                        MeMessageBox.ShowInformation("该店铺接口已经存在!");
                        return;
                    }
                    MeMessageBox.ShowInformation(txtAccount.Text + "的店铺接口添加成功!");
                    DataFactory.Accounts.Add(new Account() { TopCodeReturn = strParam, TopSession = txtTopSession.Text, AccountId = txtAccount.Text, AppKey = txtAppKey.Text, AppSecret = txtAppSecret.Text, Default = DataFactory.Accounts != null && DataFactory.Accounts.Count <= 0 ? true : false });
                }
                else
                {
                    account.TopCodeReturn = strParam;
                    account.TopSession = txtTopSession.Text;
                    account.AccountId = txtAccount.Text;
                    account.AppKey = txtAppKey.Text;
                    account.AppSecret = txtAppSecret.Text;
                    MeMessageBox.ShowInformation(txtAccount.Text + "的店铺接口修改成功!");
                }

                DialogResult = DialogResult.Yes;
                this.Close();
            }
            else if (!string.IsNullOrEmpty(nick))
            {
                MeMessageBox.ShowInformation("您所输入的Appkey和AppSecret对应的掌柜不是" + txtAccount.Text + "，而是" + nick + "的");
                return;
            }
            else
            {
                MeMessageBox.ShowError("AppKey/AppSecret无效，请点击帮助，查看如何添加店铺接口！");
                return;
            }
        }

        internal static bool TestAccount(string nick, string appkey, string appSecret,string sessionKey, out string nickAlias)
        {
            nickAlias = "";
            ITopClient client = new DefaultTopClient(UtilHelper.TAOBAO_API_URL, appkey, appSecret);
            UserGetRequest request = new UserGetRequest
            {
                Fields = "nick,last_visit"
            };
            
            for (int i = 0; i < 3; i++)
            {//sessionKey
                UserGetResponse response = client.Execute<UserGetResponse>(request, sessionKey);
                if (!response.IsError)
                {
                    nickAlias = response.User.Nick;
                    return response.User.Nick == nick;
                    //nickAlias = response.User.Nick;
                    //return (response.User.Nick == nick);
                }
                Thread.Sleep(500);
            }
            return true;
        }

        //bool TestAccount()
        //{
        //    ITopClient client = new DefaultTopClient(UtilHelper.TAOBAO__API_URL, txtAppKey.Text, txtAppSecret.Text);
        //    UserGetRequest req = new UserGetRequest();
        //    req.Fields = "user_id,nick,created,buyer_credit,type,sex";
        //   // req.Nick = txtAccount.Text;
        //    UserGetResponse rsp = client.Execute(req);//执行API请求并将该类转换为response对象
        //    if (rsp.User == null)
        //    {
        //        MeMessageBox.ShowInformation(rsp.ErrMsg);
        //        return false;
        //    }
        //    return true;
        //}

        private void btnCancle_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
            this.Close();
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            UtilHelper.RunBrowser(UtilHelper.HELP_BASE_URL + "57.html");
        }

        private void btnGetSSK_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }

            frmTopSession ssk = new frmTopSession(txtAccount.Text, txtAppKey.Text, txtAppSecret.Text);
            DialogResult result = ssk.ShowDialog();
            if (result == DialogResult.Yes)
            {
                if (ssk.Top_Session != null && ssk.Top_Session.ContainsKey(UtilHelper.TAOBAO_TOP_SESSION_STR))
                {
                    //strParam = Encoding.UTF8.GetString(Convert.FromBase64String(ssk.ParamStr));
                    strParam = ssk.ParamStr;
                    txtTopSession.Text = ssk.Top_Session[UtilHelper.TAOBAO_TOP_SESSION_STR];
                }
            }
        }
    }
}